package cn.legend.travel.admin.authorize.controller;

import cn.legend.travel.admin.authorize.pojo.param.RoleAddNewParam;
import cn.legend.travel.admin.authorize.pojo.param.RoleUpdateParam;
import cn.legend.travel.admin.authorize.service.IRoleService;
import cn.legend.travel.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.hibernate.validator.constraints.Range;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "角色管理模块")
@RestController
@Validated
@RequestMapping("roles")
@RequiredArgsConstructor
public class RoleController {
    private final IRoleService roleService;

    @GetMapping("getAll")
    @ApiOperation("查询全部角色")
    @PreAuthorize("hasAuthority('/roles/getAll')")
    public JsonResult selectAll() {
        return JsonResult.ok(roleService.getAll());
    }

    @PostMapping("addNewPermission")
    @ApiOperation("给角色增加权限")
    @PreAuthorize("hasAuthority('/roles/update')")
    public JsonResult addNewPermission(@RequestParam @Range(min = 3, message = "id为1,2的角色权限不允许被修改") Long roleId, @RequestParam Long apiId) {
        roleService.addNewPermission(roleId, apiId);
        return JsonResult.ok();
    }

    @PostMapping("deletePermission")
    @ApiOperation("删除角色的某个权限")
    @PreAuthorize("hasAuthority('/roles/update')")
    public JsonResult deletePermission(@RequestParam @Range(min = 3, message = "id为1,2的角色权限不允许被修改") Long roleId, @RequestParam Long apiId) {
        roleService.deletePermission(roleId, apiId);
        return JsonResult.ok();
    }

    @PostMapping("addNew")
    @ApiOperation("增加角色")
    @PreAuthorize("hasAuthority('/roles/addNew')")
    public JsonResult addNew(@RequestBody RoleAddNewParam param) {
        roleService.addNew(param);
        return JsonResult.ok();
    }

    @PostMapping("update")
    @ApiOperation("更改角色")
    @PreAuthorize("hasAuthority('/roles/update')")
    public JsonResult update(@Validated @RequestBody RoleUpdateParam param) {
        roleService.update(param);
        return JsonResult.ok();
    }

    @PostMapping("delete")
    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('/roles/delete')")
    public JsonResult delete(@RequestParam @Range(min = 3, message = "id为1,2的角色权限不允许被修改") Long roleId) {
        roleService.delete(roleId);
        return JsonResult.ok();
    }
}
